import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.sql.*;
import javax.imageio.ImageIO;
import javax.swing.*;

public class ReadVotes {
    // JDBC 参数，请根据实际环境调整
    private static final String JDBC_URL = "jdbc:mysql://localhost:3306/votes"
            + "?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
    private static final String JDBC_USER = "root";
    private static final String JDBC_PASS = "your_password_for_mysql";

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Votes Image Viewer");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLayout(new BorderLayout());

            // 主面板：垂直排列所有记录
            JPanel content = new JPanel();
            content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
            JScrollPane scrollPane = new JScrollPane(content);
            frame.add(scrollPane, BorderLayout.CENTER);

            // 加载并展示数据
            try (Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASS);
                 Statement stmt = conn.createStatement();
                 ResultSet rs = stmt.executeQuery("SELECT image_data, image_name, vote_count FROM images")) {

                while (rs.next()) {
                    byte[] blob = rs.getBytes("image_data");
                    String name = rs.getString("image_name");
                    int votes = rs.getInt("vote_count");

                    // 将 BLOB 转成 BufferedImage
                    BufferedImage img = ImageIO.read(new ByteArrayInputStream(blob));
                    if (img == null) continue;

                    // 创建单条记录面板
                    JPanel panel = new JPanel();
                    panel.setLayout(new BorderLayout(10, 10));
                    panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

                    // 图片标签
                    JLabel picLabel = new JLabel(new ImageIcon(img));
                    panel.add(picLabel, BorderLayout.WEST);

                    // 文字信息
                    String infoText = "<html><b>Name:</b> " + name +
                            "<br><b>Votes:</b> " + votes + "</html>";
                    JLabel infoLabel = new JLabel(infoText);
                    infoLabel.setVerticalAlignment(SwingConstants.TOP);
                    panel.add(infoLabel, BorderLayout.CENTER);

                    content.add(panel);
                }

            } catch (Exception e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(frame,
                        "Error loading images:\n" + e.getMessage(),
                        "Error", JOptionPane.ERROR_MESSAGE);
            }

            frame.setSize(800, 600);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }
}
